package com.swancloud.core.transport.propagation;

import com.swancloud.api.exceptions.ResponseException;
import com.swancloud.core.transport.HttpResponse;
import com.swancloud.core.transport.PropagateResponse;
import com.swancloud.core.transport.functions.ResponseToActionResponse;
import com.swancloud.model.common.ActionResponse;

/**
 * Propagates an exception based on the specified Status code
 *
 * @author Jeremy Unruh
 */
public class PropagateOnStatus implements PropagateResponse {

    private final int statusCode;

    private PropagateOnStatus(int statusCode) {
        this.statusCode = statusCode;
    }

    public static PropagateOnStatus on(int statusCode) {
        return new PropagateOnStatus(statusCode);
    }

    @Override
    public void propagate(HttpResponse response) {
        if (response.getStatus() == statusCode) {
            ActionResponse ar = ResponseToActionResponse.INSTANCE.apply(response);
            throw ResponseException.mapException(response, ar.getFault());
        }
    }

}
